package org.macpro.alone.prisist.common;

import java.math.BigInteger;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/** 复杂查询持久化类
 * @author 王东
 *
 */
public class LimitQueryForPage implements LimitQueryForPageInter {
	
	private String SqlTempel = " select * ";// 默认查询头
	private final String SqlSelectSize= " select count(*) num "; //默认查询数量头
	private Object entityObj;//转义对象
	private int firstResourt;//开始条数
	private int sizeResourt;//单页显示
	
	private SessionFactory sessionFatory;
	
	


	/* (non-Javadoc)
	 * @see org.macpro.alone.prisist.common.LimitQueryForPageInter#InitPara(int, int)
	 */
	public LimitQueryForPageInter InitPara(int first,int size){
		firstResourt=first;
		 sizeResourt=size;
		return this;
	}
	public LimitQueryForPageInter InitPara(int first,int size,String selectSql){
		 SqlTempel=selectSql;
		 firstResourt=first;
		 sizeResourt=size;
		return this;
	}
	/* (non-Javadoc)
	 * @see org.macpro.alone.prisist.common.LimitQueryForPageInter#runLimitQuery()
	 */
	@SuppressWarnings("unchecked")
	public List<Object> runLimitQuery(String Sqlpart,Object classObj) {
		this.entityObj=classObj;
		Session session_ = sessionFatory.openSession();
		SQLQuery sqlQuery= session_.createSQLQuery(SqlTempel+Sqlpart).addEntity(entityObj.getClass());
		sqlQuery.setFirstResult(firstResourt);
		sqlQuery.setMaxResults(sizeResourt);
		List list=sqlQuery.list();
		session_.close();
		return list;
	}
	@SuppressWarnings("unchecked")
	public List<Object> runLimitQuery(String Sql) {
		Session session_ = sessionFatory.openSession();
		SQLQuery sqlQuery= session_.createSQLQuery(Sql);
		sqlQuery.setFirstResult(firstResourt);
		sqlQuery.setMaxResults(sizeResourt);
		List list=sqlQuery.list();
		session_.close();
		return list;
	}
	/* (non-Javadoc)
	 * @see org.macpro.alone.prisist.common.LimitQueryForPageInter#runLimitQueryNum()
	 */
	public int runLimitQueryNum(String Sqlpart) {
		Session session_ = sessionFatory.openSession();
		SQLQuery sqlQuery= session_.createSQLQuery(SqlSelectSize+Sqlpart);
		Object num= sqlQuery.list().get(0);
		BigInteger renum=(BigInteger)num;
		int n=renum.intValue();
		session_.close();
		return n;
	}
	
	public SessionFactory getSessionFatory() {
		return sessionFatory;
	}
	public void setSessionFatory(SessionFactory sessionFatory) {
		this.sessionFatory = sessionFatory;
	}
}
